import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

function  Square(params) {
    return(
      <button className="square" onClick={params.onClick}>
        {params.value}
      </button>
    )  
}

class Board extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      squares: Array(9).fill(null),
      xIsNext:true
    };
  }

  handleClick(i){
    const squares=this.state.squares.slice()
    if(calculateWinner(squares)||squares[i]){
      return
    }
    squares[i]=this.state.xIsNext?"X":"O";
    this.setState({
      squares:squares,
      xIsNext:!this.state.xIsNext
    })
  }
  renderSquare(i){
    return (
    <Square
      value={this.state.squares[i]}
      onClick={() => this.handleClick(i)}
      />
    )
  }
  render(){
    const winner=calculateWinner(this.state.squares)
    let title
    if(winner){
      title ="胜利者:"+winner
    }else{
      title ="下一步出棋:"+(this.state.xIsNext?"X":"O")
    }
  
    return (
      <div className="game-board">
         <div className="title">{title}</div>
        <div className="board">
           <div className="row">
             {this.renderSquare(0)}
             {this.renderSquare(1)}
             {this.renderSquare(2)}
           </div>
           <div className="row">
             {this.renderSquare(3)}
             {this.renderSquare(4)}
             {this.renderSquare(5)}
           </div>
           <div className="row">
             {this.renderSquare(6)}
             {this.renderSquare(7)}
             {this.renderSquare(8)}
           </div>
        </div>
      </div>
    )
  }
}

class Game extends React.Component {
  render(){
 
    return (
    <div className="box">
     
     
        <Board />
      </div>
    
    );
  }
}



ReactDOM.render(
  <Game />,
  document.getElementById('root')
);
function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [0, 4, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 4, 6],
    [2, 5, 8],
    [3, 4, 5],
    [6, 7, 8]
  ]
  var is =null
   lines.forEach((item, i, arr) => {
    const [a, b, c] = arr[i]
    if(squares[a] && squares[a] === squares[b] && squares[a] === squares[c]){
      is=squares[a]
    }
  })
  return is
}
